// 导入bcrypt加密中间件
const bcrypt = require('bcrypt')
// 导入数据库
const db = require('../db/index')
// 引入crypto库生成uuid
const crypto = require('crypto')
// 导入fs处理文件路径
const fs = require('node:fs')

// 上传头像接口 files
exports.uploadAvatar = (req, res) => {
    // 生成唯一标识
    const onlyId = crypto.randomUUID()
    const oldName = req.files[0].filename
    const newName = Buffer.from(req.files[0].originalname, 'latin1').toString('utf8')
    // 在本地存储图片
    fs.renameSync('./public/upload/' + oldName, './public/upload/' + newName)
    // 数据库中插入图片地址imageUrl 和 onlyId
    const sql1 = 'insert into image set ?'
    db.query(sql1, {
        imageUrl: `http://127.0.0.1:3007/upload/${newName}`,
        onlyId: onlyId,
    }, (err, results) => {
        if (err) return res.cc(err)
        res.send({
            onlyId,
            status: 0,
            url: `http://127.0.0.1:3007/upload/${newName}`
        })
    })
}

// 头像绑定账号的接口 onlyId account url =>
exports.bindAccount = (req, res) => {
    const { onlyId, account, url } = req.body
    const sql1 = 'update image set account = ? where onlyId = ?'
    db.query(sql1, [account, onlyId], (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows === 1) {
            const sql2 = 'update users set imageUrl = ?,update_time = ? where account = ?'
            db.query(sql2, [url, new Date(), account], (err, results) => {
                if (err) return res.cc(err)
                res.send({
                    status: 0,
                    message: '修改头像成功'
                })
            })
        }
    })
}

// 修改用户密码接口 id oldPassword newPassword =>
exports.changePassword = (req, res) => {
    const { id, oldPassword } = req.body
    let { newPassword } = req.body
    // 数据库中寻找密码
    const sql1 = 'select password from users where id = ?'
    db.query(sql1, id, (err, results) => {
        if (err) return res.cc(err)
        // 输入的旧密码与密码验证
        const compareResult = bcrypt.compareSync(oldPassword, results[0].password)
        if (!compareResult) {//如果不一致
            return res.send({
                status: 1,
                message: '原密码输入错误'
            })
        }
        // 使用加密中间件bcrypt.js，对新密码进行加密后的长度为10
        newPassword = bcrypt.hashSync(newPassword, 10)
        const sql2 = 'update users set password = ?,update_time = ? where id = ?'
        db.query(sql2, [newPassword, new Date(), id], (err, results) => {
            if (err) return res.cc(err)
            res.send({
                status: 0,
                message: '修改成功'
            })
        })

    })
}

// 获取用户信息接口 id =>
exports.getUserInfo = (req, res) => {
    const sql1 = 'select * from users where id = ?'
    db.query(sql1, req.body.id, (err, results) => {
        if (err) return res.cc(err)
        results[0].password = '******'
        res.send(results[0])
    })
}

// 修改姓名接口 id name =>
exports.changeName = (req, res) => {
    const { id, name } = req.body
    const sql1 = 'update users set name = ?,update_time = ? where id = ?'
    db.query(sql1, [name, new Date(), id], (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 0,
            message: '修改姓名成功'
        })
    })
}

// 修改性别接口 id gender =>
exports.changeGender = (req, res) => {
    const { id, gender } = req.body
    const sql1 = 'update users set gender = ?,update_time = ? where id = ?'
    db.query(sql1, [gender, new Date(), id], (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 0,
            message: '修改性别成功'
        })
    })
}

// 修改邮箱接口 id email =>
exports.changeEmail = (req, res) => {
    const { id, email } = req.body
    const sql1 = 'update users set email = ?, update_time = ? where id = ?'
    db.query(sql1, [email, new Date(), id], (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 0,
            message: '修改邮箱成功'
        })
    })
}

// 忘记密码第一步：验证账户和邮箱是否一致接口 account email =>
exports.verifyAccountAndEmail = (req, res) => {
    const { account, email } = req.body
    const sql1 = 'select * from users where account = ?'
    db.query(sql1, account, (err, results) => {
        if (err) return res.cc(err)
        // 判断数据库中是否存在该account
        if (results.length !== 1) {
            return res.send({
                status: 1,
                message: '该账号未被注册'
            })
        }
        // 判断输入的email和数据库中的email是否一致
        if (email !== results[0].email) {
            return res.send({
                status: 1,
                message: '验证信息不一致'
            })
        }
        // 返回验证成功信息
        res.send({
            status: 0,
            message: '验证信息通过'
        })
    })
}

// 忘记密码第二步：设置新密码接口 account newPassword =>
exports.changePasswordInLogin = (req, res) => {
    let { account, newPassword } = req.body
    // 使用加密中间件bcrypt.js，对新密码进行加密后的长度为10
    newPassword = bcrypt.hashSync(newPassword, 10)
    const sql1 = 'update users set password = ? where account = ?'
    db.query(sql1, [newPassword, account], (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 0,
            message: '修改密码成功'
        })
    })
}

// *************************用户管理****************************
// 新建管理员接口 account password identity name gender department email =>
exports.createAdmin = (req, res) => {
    const { account, identity, name, gender, department, email } = req.body
    let { password } = req.body
    // 1.判断前端传过来的账号是否存在数据表中
    const sql1 = 'select * from users where account = ?'
    db.query(sql1, account, (err, results) => {
        if (results.length > 0) {
            return res.send({
                status: 1,
                message: '账号已存在'
            })
        }
        // 2.使用加密中间件bcrypt.js，对密码进行加密后的长度为10
        password = bcrypt.hashSync(password, 10)
        // 3.将账号和密码插入到数据表中
        const sql2 = 'insert into users set ?'
        db.query(sql2, {//sql语句/传入参数/函数
            account, password, identity, name, gender, department, email,
            create_time: new Date(),
            update_time: new Date(),
            status: 0
        }, (err, results) => {
            if (results.affectedRows !== 1) {
                return res.send({
                    status: 1,
                    message: '新建管理员失败'
                })
            }
            return res.send({
                status: 0,
                message: '新建管理员成功'
            })
        })
    })
}

// 获取管理员列表接口 identity =>
exports.getAdminList = (req, res) => {
    const { identity } = req.body
    const sql1 = "select * from users where identity = ?"
    db.query(sql1, identity, (err, results) => {
        if (err) return res.cc(err)
        results.forEach(e => {
            e.password = null
            e.create_time = null
            e.imageUrl = null
            e.status = null
        });
        res.send(results)
    })
}

// 编辑管理员信息账号接口 id name gender email department =>
exports.editAdmin = (req, res) => {
    const { id, name, gender, email, department } = req.body
    const sql1 = "select department from users where id = ?"
    const sql2 = "update users set ? where id = ?"
    db.query(sql1, id, (err, result) => {
        if (err) return res.cc(err)
        if (result[0].department === department) {
            db.query(sql2, [{
                name, gender, email, department, update_time: new Date()
            }, id], (err, results) => {
                if (err) return res.cc(err)
                res.send({
                    status: 0,
                    message: '编辑管理员信息成功，未重置部门消息列表状态'
                })
            })
        } else {
            db.query(sql2, [{
                name, gender, email, department, update_time: new Date(), read_list: null, read_status: null
            }, id], (err, results) => {
                if (err) return res.cc(err)
                res.send({
                    status: 0,
                    message: '编辑管理员信息成功，并重置部门消息列表状态'
                })
            })
        }
    })
}

// 身份降级和赋权接口 id identity =>
exports.changeIdentity = (req, res) => {
    const { id, identity } = req.body
    const sql1 = "update users set identity = ?, update_time = ? where id = ?"
    db.query(sql1, [identity, new Date(), id], (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 0,
            message: '修改身份成功'
        })
    })
}

// 通过账号对用户进行搜索接口 account,identity  =>
exports.searchUser = (req, res) => {
    const { account, identity } = req.body
    const sql1 = "select * from users where account = ? and identity = ?"
    db.query(sql1, [account, identity], (err, results) => {
        if (err) return res.cc(err)
        results.forEach(e => {
            e.password = null
            e.create_time = null
            e.imageUrl = null
        });
        res.send(results)
    })
}

// 通过部门对用户进行筛选接口 department =>
exports.searchByDepartment = (req, res) => {
    const { department } = req.body
    const sql1 = "select * from users where department = ? and identity = '用户'"
    db.query(sql1, department, (err, results) => {
        if (err) return res.cc(err)
        results.forEach(e => {
            e.password = null
            e.imageUrl = null
        })
        res.send(results)
    })
}

// 冻结或解冻用户账户接口 id =>
exports.changeStatus = (req, res) => {
    const { id } = req.body
    // 1.查找要操作账号的状态
    const sql1 = "select status from users where id = ?"
    db.query(sql1, id, (err, results) => {
        if (err) return res.cc(err)
        // 2.冻结就解冻，正常就冻结，冻结：status:1
        const status = results[0].status ? 0 : 1
        const sql2 = "update users set status = ?, update_time = ? where id = ?"
        // 3.修改状态
        db.query(sql2, [status, new Date(), id], (err, results) => {
            if (err) return res.cc(err)
            res.send({
                status: 0,
                message: status ? '冻结' : '解冻'
            })
        })
    })

}

// 获取被冻结用户列表接口 无 =>
exports.getBanList = (req, res) => {
    const sql1 = "select * from users where status = 1 and identity = '用户'"
    db.query(sql1, (err, results) => {
        if (err) return res.cc(err)
        res.send(results)
    })
}

// 删除用户接口（注销） id account =>
exports.deleteUser = (req, res) => {
    const { id, account } = req.body
    // 删除用户表里的信息
    const sql1 = "delete from users where id = ?"
    db.query(sql1, id, (err, results) => {
        if (err) return res.cc(err)
        // 删除图片表里的信息
        const sql2 = "delete from image where account = ?"
        db.query(sql2, account, (err, results) => {
            if (err) return res.cc(err)
            res.send({
                status: 0,
                message: '注销用户成功'
            })
        })
    })
}
// 分页实现=============================
// 获取对应身份的总人数 identity =>
exports.getAdminListLength = (req, res) => {
    const { identity } = req.body
    const sql1 = "select * from users where identity = ?"
    db.query(sql1, identity, (err, results) => {
        if (err) return res.cc(err)
        res.send({
            length: results.length
        })
    })
}

// 监听换页返回该页数据 页码pager identitiy =>
exports.returnListData = (req, res) => {
    const { pager, identity } = req.body
    const number = (pager - 1) * 10
    // limit 10 offset ${pager} 表示从第pager个起取10个
    const sql1 = `select * from users where identity = ? limit 10 offset ${number}`
    db.query(sql1, identity, (err, results) => {
        if (err) {
            return res.cc(err)
        }
        res.send(results)
    })
}